
package cz.swosh.stomp.web;



import org.apache.openejb.assembler.classic.EnterpriseBeanInfo;
import org.mortbay.jetty.servlet.ServletHandler;

import javax.ejb.EJB;
import javax.naming.InitialContext;
import javax.servlet.Servlet;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * Handler pro servlety peo servr Jetty. Injektuje servletům ejb.
 * @author převzato z http://openejb.apache.org/functional-testing-with-openejb-jetty-and-selenium.html
 */
public class EmbeddedServerServletHandler extends ServletHandler {
    private InitialContext initialContext;

    public EmbeddedServerServletHandler(InitialContext initialContext) {
        this.initialContext = initialContext;
    }

    public Servlet customizeServlet(Servlet servlet) throws Exception {
        Class<? extends Servlet> servletClass = servlet.getClass();
        Field[] declaredFields = servletClass.getDeclaredFields();

        for (Field declaredField : declaredFields) {
            Annotation[] annotations = declaredField.getAnnotations();

            for (Annotation annotation : annotations) {
                if (EJB.class.equals(annotation.annotationType())) {
                    // inject into this field
                    Class<?> fieldType = declaredField.getType();
                    EnterpriseBeanInfo beanInfo = getBeanFor(fieldType);
                    if (beanInfo == null) {
                        continue;
                    }
                    
                    String jndiName = "java:openejb/ejb/" + beanInfo.jndiNames.get(0);
                    // Tady asi bude dělat problémy rozdíl mezi local a remote interfejsy
                    Object o = initialContext.lookup(jndiName);

                    declaredField.setAccessible(true);
                    declaredField.set(servlet, o);
                }
            }
        }

        return super.customizeServlet(servlet);
    }

    private EnterpriseBeanInfo getBeanFor(Class<?> fieldType) {
        return new EJBHelper().getBeanInfo(fieldType);
    }
}
